package com.ruoyi.common.utils.huoshan;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.file.FileUtils;
import com.volcengine.service.visual.IVisualService;
import com.volcengine.service.visual.impl.VisualServiceImpl;
import org.noear.snack.ONode;
import org.springframework.util.CollectionUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Base64;

public class CVProcessUtil {
    public static String convertImageToBase64(String imagePath)  {
        // 读取图片文件
        File file = new File(imagePath);
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }

        // 创建字节数组
        byte[] bytes = new byte[(int) file.length()];
        try {
            fileInputStream.read(bytes);
            fileInputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        // 使用Base64编码
        return Base64.getEncoder().encodeToString(bytes);
    }
    public static String generations(String path,String prompt,String picStyle,Double fidelity)  {
        String result = "";
        IVisualService visualService = VisualServiceImpl.getInstance();
        // call below method if you dont set ak and sk in ～/.vcloud/config
        visualService.setAccessKey("AKLTNmQzNDRiY2M5ZTJiNDIwODg4MDJiMmIwMWVlY2JlMTM");
        visualService.setSecretKey("TjJRd05UVmhNemhpWW1JeE5EVTVNbUl5T0dFeVlUSmpPV1U1WlRabE9HRQ==");

        String imgBasee64 = convertImageToBase64(path);
        JSONObject req=new JSONObject();
        ArrayList<String> binaryData = new ArrayList<>();
        binaryData.add(imgBasee64);
        req.put("req_key","byteedit_v2.0");
        req.put("binary_data_base64",binaryData);
        req.put("scale",fidelity);
        req.put("return_url",true);
        req.put("prompt",prompt);

        try {
            Object response = visualService.cvProcess(req);
            System.out.println(JSON.toJSONString(response));
            ONode oNode = ONode.load(response);
            ArrayList<String> imageList=oNode.select("$.data.image_urls").toObject(ArrayList.class);
            //专为实物3000另换盘符
            if(!CollectionUtils.isEmpty(imageList)){
                result = imageList.get(0);

                String newDriveLetter = "E"; // 新的驱动器字母
                // 创建原始路径对象
                Path original = Paths.get(path);


                // 创建新的路径
                Path newPath = Paths.get(newDriveLetter + original.toString().substring(1));
                File file = new File(newPath.toString());
                String fileName = FileUtils.getNameNotSuffix(path);
                String[] laNames = fileName.split("_");

                String laName = laNames[0] + "_" + laNames[1];
                fileName = laName + "_" + picStyle; // 自定义文件名
                String parentPath = file.getParent();
                String saveDir = parentPath+"/"+fileName;
               downloadImage(result, saveDir, fileName, ".jpg");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return  result;
    }


    public static boolean decodeBase64ToImage(String base64String, String outputPath) {
        // 去除 Base64 字符串中的数据头，例如 "data:image/png;base64,"
        if (base64String.startsWith("data:image")) {
            base64String = base64String.split(",")[1];
        }

        try {
            // 创建目标文件夹（如果不存在）
            File outputFile = new File(outputPath);
            outputFile.getParentFile().mkdirs();  // 创建父级目录（如果不存在）

            // 解码 Base64 字符串
            byte[] imageBytes = Base64.getDecoder().decode(base64String);

            // 写入文件
            try (FileOutputStream fileOutputStream = new FileOutputStream(outputPath)) {
                fileOutputStream.write(imageBytes);
            }

            return true; // 成功
        } catch (IOException e) {
            e.printStackTrace();
            return false; // 失败
        }
    }
    public static void downloadImage(String imageUrl, String saveDir, String baseFileName, String fileExtension) {

        String path="";
        try {
            // 创建文件夹
            File directory = new File(saveDir);
            if (!directory.exists()) {
                directory.mkdirs();
            }

            // 确定文件名
            String fileName = baseFileName + fileExtension;
            File file = new File(directory, fileName);
            int counter = 1;

            while (file.exists()) {
                fileName = baseFileName + "_" + counter + fileExtension;
                file = new File(directory, fileName);
                counter++;
            }

            // 创建 URL 对象
            URL url = new URL(imageUrl);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("GET");
            httpConn.setConnectTimeout(5000);
            httpConn.setReadTimeout(5000);

            // 检查响应码
            if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                // 输入流
                InputStream inputStream = httpConn.getInputStream();
                // 输出流
                FileOutputStream outputStream = new FileOutputStream(file);

                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                outputStream.close();
                inputStream.close();
                System.out.println("图片下载成功: " + file.getAbsolutePath());
                path =  file.getAbsolutePath();
            } else {
                System.out.println("无效的响应代码: " + httpConn.getResponseCode());
            }
            httpConn.disconnect();
        } catch (IOException e) {
            System.out.println("报错下载链接："+ path);
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        generations("E:\\workdata\\码诚科技\\2025年\\图片生成三星\\accessory\\accessory\\bindi\\bindi1.jpg","Comic (Illustration)\n" +
                "Portrait studio:\n" +
                ": 2D form of simplified light and shade representation with realistic depiction, clear outline, \n" +
                "simplified to two or three tones, strong colors，","MH",0.9);
    }

}